<template>
  <div class="system-user-dialog-container">
    <!--    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">-->
    <CustomDialog
        :title="state.dialog.title"
        v-model:visible="state.dialog.isShowDialog"
        dialogWidth="900px"
        @close="closeDialog"
        :showSubmit="true"
        :dialogFooterBtn="true"
    >
      <el-form ref="userDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="账户名称" prop="username">
              <el-input v-model="state.ruleForm.username" placeholder="请输入账户名称" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="state.ruleForm.nickname" placeholder="请输入用户昵称" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="用户姓名" prop="realName">
              <el-input v-model="state.ruleForm.realName" placeholder="请输入用户姓名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="部门" prop="deptId">
              <el-cascader
                  :options="state.deptData"
                  :props="{ checkStrictly: true, value: 'id', label: 'deptName', emitPath: false }"
                  placeholder="请选择部门"
                  clearable
                  class="w100"
                  v-model="state.ruleForm.deptId"
              >
                <template #default="{ node, data }">
                  <span>{{ data.deptName }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="state.ruleForm.mobile" placeholder="请输入手机号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="state.ruleForm.email" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="state.ruleForm.gender" placeholder="请选择" clearable class="w100">
                <el-option label="男" :value="0"></el-option>
                <el-option label="女" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="省市区" prop="regionData">
              <el-cascader placeholder="请选择省市区" class="w100" clearable :options="state.regionData"
                           v-model="state.choiceRegionData">
              </el-cascader>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="账户密码">
              <el-input v-model="state.ruleForm.password" placeholder="请输入" type="password" clearable></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="出生时间" prop="birthdayFormat">
              <el-date-picker v-model="state.ruleForm.birthdayFormat" type="datetime" placeholder="请选择出生时间"
                              class="w100"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="账户过期" prop="expirationFormat">
              <el-date-picker v-model="state.ruleForm.expirationFormat" type="datetime" placeholder="请选择到期时间"
                              class="w100"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="用户状态" prop="userStatus">
              <el-switch
                  v-model="state.ruleForm.userStatus"
                  inline-prompt
                  active-text="启"
                  inactive-text="禁"
                  :active-value="1"
                  :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="选择角色">
              <el-checkbox-group v-model="state.choiceRoleIds" class="role-checkbox-group">
                <el-checkbox v-for="role in state.roleInfos" :key="role.id" :label="role.id" name="roleId">
                  {{ role.roleName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col
          >

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="用户地址" prop="address">
              <el-input v-model="state.ruleForm.address" type="textarea" placeholder="请输入用户详细地址"
                        maxlength="150"></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="用户描述" prop="description">
              <el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入用户描述"
                        maxlength="150"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(userDialogFormRef)" size="default">{{
              state.dialog.submitTxt
            }}</el-button>
				</span>
      </template>
    </CustomDialog>
    <!--    </el-dialog>-->
  </div>
</template>

<script setup lang="ts" name="systemUserDialog">
import {reactive, ref, nextTick} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {pcaTextArr} from 'element-china-area-data';
import {userApi} from '/@/api/sys/user/index';
import {roleApi} from '/@/api/sys/role/index';
import {deptApi} from '/@/api/sys/dept/index';
import msg from '/@/utils/messageUtils';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    id: '',
    username: '',
    nickname: '', // 用户昵称
    realName: '',
    roleSign: '', // 关联角色
    mobile: '', // 手机号
    email: '', // 邮箱
    gender: '0', // 性别
    password: '',
    expiration: 0,
    deptId: '',
    userStatus: 0, // 用户状态
    description: '', // 用户描述
    expirationFormat: '',
    birthdayFormat: '',
    birthday: 0,
    roleIds: [],
    address: '',
    regionData: '',
    region: '',
  },
  deptData: [] as DeptTreeType[], // 部门数据
  roleInfos: [],
  choiceRoleIds: [],
  regionData: pcaTextArr,
  choiceRegionData: [],
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
});
var checkMobile = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('手机号不可为空'));
  } else {
    if (value !== '') {
      var reg = /^1[3-9]\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error('请输入有效的手机号码'));
      }
    }
    callback();
  }
};
var checkEmail = (rule, value, cb) => {
  //验证邮箱的正则表达式
  const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  if (regEmail.test(value)) {
    //合法的邮箱
    return cb();
  }
  cb(new Error('请输入合法的邮箱'));
};

const rules = reactive<FormRules>({
  username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
  nickname: [{required: true, message: '用户昵称不能为空', trigger: 'blur'}],
  mobile: [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {
      validator: checkMobile,
      min: 11,
      max: 11,
      message: '手机号格式错误',
      trigger: 'blur',
    },
  ],
  email: [
    {required: true, message: 'email不能为空', trigger: 'blur'},
    {
      validator: checkEmail,
      min: 9,
      max: 18,
      message: '邮箱格式错误',
      trigger: 'blur',
    },
  ],
  expirationFormat: [{required: true, message: '账号过期时间不能为空', trigger: 'blur'}],
  deptId: [{required: true, message: '所属部门不能为空', trigger: 'blur'}],
  birthdayFormat: [{required: true, message: '出生年月不能为空', trigger: 'blur'}],
});
// 打开弹窗
const openDialog = (type: string, row: any) => {
  state.choiceRoleIds = [];
  if (type === 'edit') {
    // todo 设置内容.....
    console.log('userId: ', row.id);
    userDetail(row.id);
    state.dialog.title = '修改用户';
    state.dialog.submitTxt = '修 改';
    state.dialog.type = 'edit';
    state.ruleForm.id = row.id;
    onChoiceRoleIdsByUserId();
    nextTick(() => {
      userDialogFormRef.value.clearValidate();
    });
  } else {
    state.dialog.title = '新增用户';
    state.dialog.submitTxt = '新 增';
    state.dialog.type = 'add';
    state.regionData = [];
    // 清空表单，此项需加表单验证才能使用
    nextTick(() => {
      userDialogFormRef.value.clearValidate();
      userDialogFormRef.value.resetFields();
    });
  }

  state.dialog.isShowDialog = true;
  getDeptData();
  onLoadAllRoleInfos();
};

const userDetail = async (userId: string) => {
  try {
    const {data} = await userApi().viewUser(userId);
    state.ruleForm = data;
    state.ruleForm.expirationFormat = data.expiration;
    state.ruleForm.birthdayFormat = data.birthday;
    state.choiceRegionData = data.region.split(',');
  } catch (error) {
    msg().error('获取详情失败');
  }
};

const onChoiceRoleIdsByUserId = async () => {
  try {
    const {data} = await userApi().userRoleIdsByUserId(state.ruleForm.id);
    state.choiceRoleIds = data;
  } catch (error) {
    msg().error('获取用户角色id信息');
  }
};

const onLoadAllRoleInfos = async () => {
  try {
    const {data} = await roleApi().allRoles();
    state.roleInfos = data;
  } catch (error) {
    msg().error('查询角色失败，请重试');
  }
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }
  await formEl.validate(async (valid) => {
    if (valid) {
      const choiceRegionData: any = [];
      state.choiceRegionData.forEach((e) => {
        choiceRegionData.push(e);
      });
      state.ruleForm.region = choiceRegionData.join(',');
      try {
        state.ruleForm.roleIds = [];
        if (state.choiceRoleIds.length > 0) {
          state.choiceRoleIds.forEach((e) => {
            state.ruleForm.roleIds.push(e);
          });
        }
        const et: any = state.ruleForm.expirationFormat;
        if (typeof et == 'string') {
          state.ruleForm.expiration = Date.parse(et);
        } else {
          state.ruleForm.expiration = et.getTime();
        }

        const bt: any = state.ruleForm.birthdayFormat;

        if (typeof bt == 'string') {
          state.ruleForm.birthday = Date.parse(bt);
        } else {
          state.ruleForm.birthday = bt.getTime();
        }

        if (state.dialog.type === 'add') {
          await userApi().createUser(state.ruleForm);
        }
        if (state.dialog.type === 'edit') {
          await userApi().updateUser(state.ruleForm);
        }
        closeDialog();
        emit('refresh');
        msg().success('操作成功');
      } catch (error) {
        msg().error('操作失败');
      }
    }
  });
};
// 初始化部门数据
const getDeptData = async () => {
  try {
    const {data} = await deptApi().tree();
    // console.log('data: ', JSON.stringify(data));
    // state.deptData.push(data);
    state.deptData = data;
  } catch (error) {
    msg().error('获取部门失败，请重试.');
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>


.role-checkbox-group {
  display: grid !important;
  width: 100%;
  //grid-template-columns: repeat(5, 1fr) !important;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)) !important;
  gap: 8px 12px !important;

  :deep(.el-checkbox) {
    margin-right: 0 !important;
    display: block !important;
    width: 100% !important;

    .el-checkbox__label {
      white-space: nowrap !important;
      overflow: hidden !important;
      text-overflow: ellipsis !important;
      max-width: 150px !important;
      display: inline-block !important;
    }
  }
}
</style>